
/**
 * 全局事件总线：GlobalEvent.ts
 * 轻量级事件系统，用于模块解耦通信，支持 context 绑定
 */

type EventCallback = (...args: any[]) => void;

type Listener = {
  callback: EventCallback;
  context?: any;
};

class EventBus {
  private events: Map<string, Set<Listener>> = new Map();

  public on(event: string, callback: EventCallback, context?: any) {
    if (!this.events.has(event)) {
      this.events.set(event, new Set());
    }
    const listeners = this.events.get(event)!;
    listeners.add({ callback, context });
  }

  public off(event: string, callback: EventCallback, context?: any) {
    const listeners = this.events.get(event);
    if (!listeners) return;

    for (const listener of listeners) {
      if (listener.callback === callback && listener.context === context) {
        listeners.delete(listener);
        break;
      }
    }
  }

  public emit(event: string, ...args: any[]) {
    this.events.get(event)?.forEach(({ callback, context }) => {
      callback.apply(context, args);
    });
  }

  public clear(event?: string) {
    if (event) {
      this.events.delete(event);
    } else {
      this.events.clear();
    }
  }
}
export const GlobalEvent = new EventBus();

